package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.lang.UUID;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.service.ValidateCodeService;
import com.atguigu.spzx.model.constant.Constant;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author：tzl
 * @Date：2024/1/23 16:46
 * @description: 校验验证码
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode() {
        // 生成验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 4);
        String code = circleCaptcha.getCode();
        String imageBase64 = circleCaptcha.getImageBase64();

        // 存储到redis中
        String codeKey = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(Constant.USER_LOGIN_VALIDATE_CODE + codeKey , code, 5, TimeUnit.MINUTES);

        // 封装返回对象
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(codeKey);

        // 验证码图片
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);
        return validateCodeVo;
    }

    @Override
    public void validateCode(LoginDto loginDto) {
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();

        String value = redisTemplate.opsForValue().get(Constant.USER_LOGIN_VALIDATE_CODE + codeKey);

        // 如果取不到验证码，或者验证码校验不正确（忽略大小写）
        if (StringUtils.isBlank(value) || !StringUtils.equalsIgnoreCase(captcha,value)) {
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

    }
}
